package result

import (
	"audio-server/internal/types"
	"fmt"

	"github.com/golang-jwt/jwt/v4"
)

const OK = 200

const FAIL = 500

func Success(data any) *types.BaseMsgResp {
	return &types.BaseMsgResp{
		Code: OK,
		Msg:  "success",
		Data: data,
	}
}

func Fail(msg string) *types.BaseMsgResp {
	return &types.BaseMsgResp{
		Code: FAIL,
		Msg:  msg,
	}
}

func GetJwtToken(secretKey string, iat, seconds int64, payload any) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["userId"] = payload
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

func GetUserIdFromToken(tokenString string, secretKey string) (any, error) {
	// 解析 token
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		// 验证签名方法
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(secretKey), nil
	})

	if err != nil {
		return nil, err
	}

	// 验证 token 是否有效
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		// 获取 userId
		userId, exists := claims["userId"]
		if !exists {
			return nil, fmt.Errorf("userId not found in token")
		}
		return userId, nil
	}

	return nil, fmt.Errorf("invalid token")
}
